/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 权限引导组件 - 用于引导用户授予必要权限
 */

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../services/permission_manager.dart';
import '../../services/ios_permission_helper.dart';

/// 权限引导组件
class PermissionGuideWidget extends StatefulWidget {
  final String title;
  final String description;
  final List<PermissionItem> permissions;
  final VoidCallback? onPermissionGranted;
  final VoidCallback? onPermissionDenied;
  final bool showCloseButton;

  const PermissionGuideWidget({
    Key? key,
    required this.title,
    required this.description,
    required this.permissions,
    this.onPermissionGranted,
    this.onPermissionDenied,
    this.showCloseButton = true,
  }) : super(key: key);

  @override
  State<PermissionGuideWidget> createState() => _PermissionGuideWidgetState();
}

class _PermissionGuideWidgetState extends State<PermissionGuideWidget> {
  bool _isRequesting = false;
  Map<Permission, PermissionStatus> _permissionStatuses = {};

  @override
  void initState() {
    super.initState();
    _checkPermissionStatuses();
  }

  /// 检查权限状态
  Future<void> _checkPermissionStatuses() async {
    final statuses = <Permission, PermissionStatus>{};
    for (final item in widget.permissions) {
      statuses[item.permission] = await item.permission.status;
    }

    if (mounted) {
      setState(() {
        _permissionStatuses = statuses;
      });
    }
  }

  /// 请求权限
  Future<void> _requestPermissions() async {
    if (_isRequesting) return;

    setState(() {
      _isRequesting = true;
    });

    try {
      bool result;

      // iOS 平台使用专门的权限处理流程
      if (Platform.isIOS) {
        result = await IOSPermissionHelper.instance.handleIOSPermissionFlow(
          context,
          widget.permissions.map((item) => item.permission).toList(),
        );
      } else {
        result = await PermissionManager.instance.requestAudioPermissions();
      }

      // 重新检查权限状态
      await _checkPermissionStatuses();

      if (!mounted) return;

      if (result) {
        // 延迟调用回调，避免在权限对话框关闭过程中导航
        Future.delayed(const Duration(milliseconds: 200), () {
          if (mounted) {
            widget.onPermissionGranted?.call();
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('设置完成，可以开始使用了！'),
                backgroundColor: Colors.green,
              ),
            );
          }
        });
      } else {
        // 权限被拒绝时显示友好提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('您仍可以继续使用应用的基础功能'),
            backgroundColor: Colors.blue,
          ),
        );
      }
    } catch (error) {
      debugPrint('PermissionGuideWidget: 请求权限失败 - $error');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('您可以继续使用应用，稍后在需要时再设置权限'),
            backgroundColor: Colors.blue,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isRequesting = false;
        });
      }
    }
  }

  /// 打开应用设置
  Future<void> _openAppSettings() async {
    try {
      final opened = await PermissionManager.instance.openSettings();
      if (!opened && mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('无法打开设置页面'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (error) {
      debugPrint('PermissionGuideWidget: 打开设置失败 - $error');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('打开设置失败: $error'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 获取权限状态图标
  Widget _getPermissionStatusIcon(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return const Icon(Icons.check_circle, color: Colors.green, size: 20);
      case PermissionStatus.denied:
        return const Icon(Icons.cancel, color: Colors.orange, size: 20);
      case PermissionStatus.permanentlyDenied:
        return const Icon(Icons.block, color: Colors.red, size: 20);
      case PermissionStatus.restricted:
        return const Icon(Icons.warning, color: Colors.amber, size: 20);
      case PermissionStatus.limited:
        return const Icon(Icons.info, color: Colors.blue, size: 20);
      default:
        return const Icon(Icons.help, color: Colors.grey, size: 20);
    }
  }

  /// 获取权限状态文本
  String _getPermissionStatusText(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return '已授予';
      case PermissionStatus.denied:
        return '被拒绝';
      case PermissionStatus.permanentlyDenied:
        return '永久拒绝';
      case PermissionStatus.restricted:
        return '受限制';
      case PermissionStatus.limited:
        return '有限授予';
      default:
        return '未知';
    }
  }

  /// 检查是否有永久拒绝的权限
  bool get _hasPermanentlyDeniedPermissions {
    return _permissionStatuses.values
        .any((status) => status == PermissionStatus.permanentlyDenied);
  }

  /// 检查是否所有权限都已授予
  bool get _allPermissionsGranted {
    return widget.permissions.every((item) {
      final status = _permissionStatuses[item.permission];
      return status == PermissionStatus.granted;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题和关闭按钮
            Row(
              children: [
                Expanded(
                  child: Text(
                    widget.title,
                    style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                ),
                if (widget.showCloseButton)
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
              ],
            ),

            const SizedBox(height: 12),

            // 描述
            Text(
              widget.description,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Colors.grey[600],
                  ),
            ),

            const SizedBox(height: 20),

            // 权限列表
            ...widget.permissions.map((item) {
              final status = _permissionStatuses[item.permission];
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 8),
                child: Row(
                  children: [
                    _getPermissionStatusIcon(status ?? PermissionStatus.denied),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item.title,
                            style: Theme.of(context)
                                .textTheme
                                .titleSmall
                                ?.copyWith(
                                  fontWeight: FontWeight.w500,
                                ),
                          ),
                          Text(
                            item.description,
                            style:
                                Theme.of(context).textTheme.bodySmall?.copyWith(
                                      color: Colors.grey[600],
                                    ),
                          ),
                        ],
                      ),
                    ),
                    Text(
                      _getPermissionStatusText(
                          status ?? PermissionStatus.denied),
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                            color: status == PermissionStatus.granted
                                ? Colors.green
                                : Colors.grey[600],
                            fontWeight: FontWeight.w500,
                          ),
                    ),
                  ],
                ),
              );
            }).toList(),

            const SizedBox(height: 24),

            // 操作按钮
            if (_allPermissionsGranted) ...[
              // 所有权限已授予
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: widget.onPermissionGranted,
                  icon: const Icon(Icons.check_circle),
                  label: const Text('继续使用'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                    foregroundColor: Colors.white,
                  ),
                ),
              ),
            ] else if (_hasPermanentlyDeniedPermissions) ...[
              // 有永久拒绝的权限，需要去设置
              Column(
                children: [
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      onPressed: _openAppSettings,
                      icon: const Icon(Icons.settings),
                      label: const Text('去设置开启权限'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        foregroundColor: Colors.white,
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  SizedBox(
                    width: double.infinity,
                    child: TextButton(
                      onPressed: _checkPermissionStatuses,
                      child: const Text('重新检查权限'),
                    ),
                  ),
                ],
              ),
            ] else ...[
              // 可以请求权限
              Column(
                children: [
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      onPressed: _isRequesting ? null : _requestPermissions,
                      icon: _isRequesting
                          ? const SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : const Icon(Icons.security),
                      label: Text(_isRequesting ? '请求中...' : '授予权限'),
                    ),
                  ),
                  const SizedBox(height: 8),
                  SizedBox(
                    width: double.infinity,
                    child: TextButton(
                      onPressed: () {
                        // 安全地处理"稍后再说"按钮
                        Future.delayed(const Duration(milliseconds: 100), () {
                          if (mounted) {
                            widget.onPermissionDenied?.call();
                          }
                        });
                      },
                      child: const Text('稍后再说'),
                    ),
                  ),
                ],
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 权限项目
class PermissionItem {
  final Permission permission;
  final String title;
  final String description;

  const PermissionItem({
    required this.permission,
    required this.title,
    required this.description,
  });
}

/// 预定义的权限项目
class PermissionItems {
  static const notification = PermissionItem(
    permission: Permission.notification,
    title: '通知权限',
    description: '用于显示播放控制和歌曲信息通知',
  );

  static const audio = PermissionItem(
    permission: Permission.audio,
    title: '音频权限',
    description: '用于播放音乐和音频文件',
  );

  static const microphone = PermissionItem(
    permission: Permission.microphone,
    title: '麦克风权限',
    description: '用于音频录制和处理功能',
  );

  /// 获取音频播放相关的权限列表
  static List<PermissionItem> get audioPlaybackPermissions => [
        notification,
      ];
}
